var fs = require('fs');
var path = require('path');
var headTitleRegular = /^.title/;
var titleRegular = /.title/g;
var headPtitleRegular = /^.ptitle/;
var ptitleRegular = /.ptitle/g;

function textToHtml(textline){
  switch(true){
    case ptitleRegular.test(textline):
      return '</br><p class="ptitle">'+ textline.replace(ptitleRegular, '') +'</p>';
    case titleRegular.test(textline):
      return '<div class="title">'+ textline.replace(titleRegular, '') +'</div>';

    default:
      return '<p>'+ textline +'</p>';
  }
}

var fileArr = fs.readdirSync(path.join(__dirname, 'text'));
var promiseArr = fileArr.map(function(fileItem){
  return new Promise(function(resolve, reject){
    fs.readFile(path.join(__dirname, 'text' , fileItem), function(err, data){
      if(err){
          reject(err);
          return;
      }

      var newData = data.toString().split('\n').map(function(item){
        return textToHtml(item);
      }).join('\n');

      newData = '<link rel="stylesheet" type="text/css" href="/css/protocal.css"/>\n' + newData;

      fs.writeFile(path.join(__dirname,  'ejs',  fileItem.split('.')[0] + '.ejs'), newData, function(err){
        if(err){
          reject(err);
          return;
        }
        resolve();
      });
    });
  });
  
});
  

Promise.all(promiseArr).then(function(){
  console.log("end");
}).catch(function(e){
  console.log(e);
});
